import Service from "../../model/service";
import Category from "../../model/category";
import {throttle} from "../../utils/utils";
import cache from "../../enum/cache";
import {setTabBarBadge} from "../../utils/wx";

const service = new Service();
Page({
  data: {
    tabs: ['全部服务', '在提供', '正在找'],
    categoryList: [],
    tabIndex: 0,
    categoryId: 0,
    currentCategoryIndex: 0,
    loading: true
  },
  onLoad: async function (options) {
    await this._getServiceList()

    await this._getCategoryList()

    this.setData({
      loading: false
    })
  },

  onShow() {
    const unreadCount = wx.getStorageSync(cache.UNREAD_COUNT)
    setTabBarBadge(unreadCount)
  },

  // 发起网络请求，获取服务列表数据
  // 接收者也要使用async/await语法
  async _getServiceList() {
    const serviceList = await service.reset().getServiceList(
      this.data.categoryId,
      this.data.tabIndex)
    // console.log('serviceList', serviceList)
    this.setData({serviceList})
  },
  async _getCategoryList() {
    const categoryList = await Category.getCategoryListWithAll()
    // console.log('categoryList', categoryList)
    this.setData({
      categoryList
    })
  },
  handleTabChange(event) {
    this.data.tabIndex = event.detail.index
    this._getServiceList()
  },
  handleCateoryChange: throttle(function (event) {
    if (this.data.categoryId === event.currentTarget.dataset.id) {
      return
    }
    this.data.categoryId = event.currentTarget.dataset.id
    this._getServiceList()
    // 分类标签切换 自己的作业
    const index = event.currentTarget.dataset.index
    this.setData({
      currentCategoryIndex: index
    })
  }),
  handleSelectService(event) {
    console.log(event)
    const service = event.currentTarget.dataset.service
    // 1.用缓存传递数据有数据不一致的风险
    //  2.只传递一个id,然后跳转后再请求
    wx.navigateTo({
      url: '/pages/service-detail/service-detail?service_id=' + service.id
    })
  },
  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    this._getServiceList()
    wx.stopPullDownRefresh()
  },
  /**
   * 上拉加载
   */
  async onReachBottom() {
    //获取下一页数据并渲染
    if (!service.hasMoreData) {
      return
    }
    const serviceList = await service.getServiceList(this.data.categoryId, this.data.tabIndex)
    this.setData({serviceList})
  }
});